package net.begincode.maiev.handler;

import net.begincode.maiev.common.BeginCodeConstant;
import net.begincode.maiev.common.BizException;
import net.begincode.maiev.enums.CommonResponseEnum;
import net.begincode.maiev.model.MaievUser;
import net.begincode.maiev.service.MaievUserService;
import net.begincode.maiev.session.SessionOperation;
import net.begincode.maiev.util.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by Stay on 2017/5/25  22:22.
 */
@Component
public class UserHandler implements UserStrategy {

    private static final Logger logger = LoggerFactory.getLogger(UserHandler.class);

    @Resource
    private MaievUserService maievUserService;


    @Resource
    private HttpSession httpSession;

    @Override
    public void login(MaievUser user) {
        MaievUser maievUser = maievUserService.getUserByUsernameAndPwd(user.getUsername(), user.getPwd());
        if (maievUser == null) {
            throw new BizException(CommonResponseEnum.DATA_NULL);
        }
        httpSession.setAttribute(BeginCodeConstant.LOGINUSER, maievUser);
    }

    @Override
    public void loginOut() {
        SessionOperation.loginOut();
    }

    @Override
    public void regist(MaievUser user) {
        try {
            String pwd = user.getPwd();
            user.setPwd(MD5Utils.md5(pwd));
            maievUserService.saveUser(user);
        } catch (BizException e) {
            logger.error(e.getMessage(), e);
            throw new BizException(CommonResponseEnum.EXCEPTION);
        }
    }

    @Override
    public MaievUser getCurrentUser() {
        return SessionOperation.getUser();
    }

    @Override
    public void checkUserName(String userName) {
        MaievUser userByUserName = maievUserService.getUserByUserName(userName);
        if (userByUserName != null) {
            throw new BizException(CommonResponseEnum.DATA_NULL);
        }
    }

    @Override
    public void checkNickName(String nickName) {
        MaievUser userByNickname = maievUserService.getUserByNickname(nickName);
        if (userByNickname != null) {
            throw new BizException(CommonResponseEnum.DATA_NULL);
        }
    }

    @Override
    public void checkEmail(String email) {
        MaievUser userByEmail = maievUserService.getUserByEmail(email);
        if (userByEmail != null) {
            throw new BizException(CommonResponseEnum.DATA_NULL);
        }
    }

    @Override
    public void checkCode(String code) {
        String attribute = (String) httpSession.getAttribute(BeginCodeConstant.VERCODE);
        if (!code.toLowerCase().equals(attribute)) {
            throw new BizException(CommonResponseEnum.PARAM_ERROR);
        }
    }

    @Override
    public MaievUser getUserById(Integer userId) {
        return maievUserService.getUserById(userId);
    }
}
